package com.yj.mvc.web.servlet.resource;

import cn.hutool.core.util.StrUtil;
import com.yj.mvc.web.core.MappingValue;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletConfig;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 读取web.xml中配置init-param的configLocation参数，并解析其中的xml配置文件，获取其中的映射关系
 */
public class XmlConfigReader {

    private ServletConfig servletConfig;

    public XmlConfigReader(ServletConfig servletConfig){
        this.servletConfig = servletConfig;
    }

    public Map<String, MappingValue> loadConfig(){
        String configLocation = servletConfig.getInitParameter("configLocation");
        if(StrUtil.isBlank(configLocation)){
            throw new IllegalArgumentException("configLocation is not set in web.xml");
        }

        SAXReader reader = new SAXReader();
        Map<String, MappingValue> mappingValueMap = new HashMap<>();
        try{
            Document document = reader.read(configLocation);
            Element rootElement = document.getRootElement();
            List elements = rootElement.elements();
            for(Object element : elements){
                Element e = (Element) element;
                String id = e.attributeValue("id");
                String className = e.attributeValue("class");
                String methodName = e.attributeValue("value");
                MappingValue mappingValue = new MappingValue(id, className, methodName);
                mappingValueMap.put(id, mappingValue);
            }
            return mappingValueMap;
        }catch (Exception e){
            throw new RuntimeException("load config error", e);
        }
    }
}
